package ui.activity.profit;

import android.content.Context;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.util.ArrayMap;
import android.widget.TextView;
import android.widget.Toast;

import com.jakewharton.rxbinding.view.RxView;
import com.kf5.sdk.helpcenter.ui.HelpCenterActivity;
import com.kf5.sdk.im.ui.KF5ChatActivity;
import com.kf5.sdk.system.entity.Field;
import com.kf5.sdk.system.entity.ParamsKey;
import com.kf5.sdk.system.init.UserInfoAPI;
import com.kf5.sdk.system.internet.HttpRequestCallBack;
import com.kf5.sdk.system.utils.SPUtils;
import com.kf5.sdk.system.utils.SafeJson;
import com.kf5.sdk.ticket.ui.FeedBackActivity;
import com.kf5.sdk.ticket.ui.LookFeedBackActivity;

import net.ck.hzq.R;

import org.json.JSONException;
import org.json.JSONObject;

import java.lang.ref.SoftReference;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import Utils.SharedPrefStore;
import base.BaseAct;
import butterknife.BindView;
import coom.Constants;
import event.NetErrorEvent;
import util.Kf5BaseUtils;
import util.LogUtils;


/**
 * 登录界面
 * Created by chenjian on 2017/8/4.
 */

public class KF5CustomerAct extends BaseAct {


    @BindView(R.id.tvHelpCenter)
    TextView helpCenter;
    @BindView(R.id.tvFeedBack)
    TextView feedBack;
    @BindView(R.id.tvLookFeedBack)
    TextView lookFeedBack;
    @BindView(R.id.tvIM)
    TextView iM;


    Map<String, String> map = new ArrayMap<>();
    SharedPrefStore store;

    @Override
    protected void setRoot() {
//        setTitleBar(R.color.colorBlue);
        setContentView(R.layout.activity_kf5_customer);

    }

    @Override
    protected void setup() {
//        DaggerProfitComponent.builder().profitModule(new ProfitModule(this)).build().inject(this);
        setToolBar(getResources().getString(R.string.customer_center), "");
    }


    @Override
    protected void init(@Nullable Bundle savedInstanceState) {
        store = new SharedPrefStore();
        if (!Constants.CustomerOline) {
            SPUtils.saveAppID(Constants.KF5SERCET);
            SPUtils.saveHelpAddress(Constants.KF5URL);
            String customId = store.getString("id", "0");
            String realName = store.getString("realname", "");
            String phone = store.getString("phonenumber", "");
            try {
                JSONObject jsonObject = new JSONObject();
                jsonObject.put(ParamsKey.PHONE, phone);
                jsonObject.put(ParamsKey.VALUE, customId);
                jsonObject.put(ParamsKey.NAME, realName);
                map.put(ParamsKey.USER_FIELDS, jsonObject.toString());
                map.put(ParamsKey.NAME, realName);
                map.put(ParamsKey.PHONE, phone);
                map.put(ParamsKey.EMAIL, customId + "@forcard.com");
                createUser();
            } catch (Exception e) {

            }
        }

        RxView.clicks(helpCenter)
                .compose(this.<Void>bindToLifecycle())
                .throttleFirst(500, TimeUnit.MILLISECONDS)
                .subscribe(Void -> startAct(HelpCenterActivity.class, null));
        RxView.clicks(feedBack)
                .compose(this.<Void>bindToLifecycle())
                .throttleFirst(500, TimeUnit.MILLISECONDS)
                .subscribe(Void -> startAct(FeedBackActivity.class, null));
        RxView.clicks(lookFeedBack)
                .compose(this.<Void>bindToLifecycle())
                .throttleFirst(500, TimeUnit.MILLISECONDS)
                .subscribe(Void -> startAct(LookFeedBackActivity.class, null));
        RxView.clicks(iM)
                .compose(this.<Void>bindToLifecycle())
                .throttleFirst(500, TimeUnit.MILLISECONDS)
                .subscribe(Void -> startAct(KF5ChatActivity.class, null));
    }


    @Override
    public void onNetErrorEvent(NetErrorEvent event) {
        super.onNetErrorEvent(event);
    }

    @Override
    protected void onNetError(NetErrorEvent event) {

    }


    @Override
    protected void onStop() {
        super.onStop();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    private void loginUser(final Map<String, String> map) {
        UserInfoAPI.getInstance().loginUser(map, new HttpRequestCallBack() {
            @Override
            public void onSuccess(final String result) {
                LogUtils.d("kf5测试", "登录成功" + result);
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            final JSONObject jsonObject = SafeJson.parseObj(result);
                            int resultCode = SafeJson.safeInt(jsonObject, "error");
                            if (resultCode == 0) {
                                final JSONObject dataObj = SafeJson.safeObject(jsonObject, Field.DATA);
                                JSONObject userObj = SafeJson.safeObject(dataObj, Field.USER);
                                if (userObj != null) {
                                    String userToken = userObj.getString(Field.USERTOKEN);
                                    int id = userObj.getInt(Field.ID);
                                    SPUtils.saveUserToken(userToken);
                                    SPUtils.saveUserId(id);
                                    saveToken(map, userToken);
                                }
                            } else {
                                runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        try {
                                            String message = jsonObject.getString("message");
                                            Toast.makeText(KF5CustomerAct.this, message, Toast.LENGTH_SHORT).show();
                                        } catch (JSONException e) {
                                            e.printStackTrace();
                                        }
                                    }
                                });
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                });
            }

            @Override
            public void onFailure(String result) {
                LogUtils.d("kf5测试", "登录失败" + result);
                Constants.CustomerOline = false;
            }
        });
    }


    private void saveToken(Map<String, String> map, String token) {
        map.put(ParamsKey.DEVICE_TOKEN, token);
        UserInfoAPI.getInstance().saveDeviceToken(map, new HttpRequestCallBack() {
            @Override
            public void onSuccess(String result) {
                LogUtils.d("kf5测试", "保存设备Token成功" + result);
            }

            @Override
            public void onFailure(String result) {
                LogUtils.d("kf5测试", "保存设备Token失败" + result);
                Constants.CustomerOline = false;
            }
        });

        UserInfoAPI.getInstance().getUserInfo(map, new HttpRequestCallBack() {
            @Override
            public void onSuccess(String result) {
            }

            @Override
            public void onFailure(String result) {
                Constants.CustomerOline = false;
            }
        });
    }

    private void createUser() {
        LogUtils.d(map.toString());
        SPUtils.saveUserAgent(Kf5BaseUtils.getAgent(new SoftReference<Context>(KF5CustomerAct.this)));
        UserInfoAPI.getInstance().createUser(map
                , new HttpRequestCallBack() {
                    @Override
                    public void onSuccess(final String result) {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                try {
                                    final JSONObject jsonObject = SafeJson.parseObj(result);
                                    int resultCode = SafeJson.safeInt(jsonObject, "error");
                                    if (resultCode == 0) {
//                                        Preference.saveBoolLogin(LoginAct.this, true);
                                        final JSONObject dataObj = SafeJson.safeObject(jsonObject, Field.DATA);
                                        JSONObject userObj = SafeJson.safeObject(dataObj, Field.USER);
                                        if (userObj != null) {
                                            String userToken = userObj.getString(Field.USERTOKEN);
                                            int id = userObj.getInt(Field.ID);
                                            SPUtils.saveUserToken(userToken);
                                            SPUtils.saveUserId(id);
                                            saveToken(map, userToken);
                                        }
                                        LogUtils.d("kf5测试", "登录成功" + result);
                                    } else {
                                        runOnUiThread(new Runnable() {
                                            @Override
                                            public void run() {
                                                loginUser(map);
                                                LogUtils.d("kf5测试");
                                            }
                                        });
                                    }
                                } catch (JSONException e) {
                                    e.printStackTrace();
                                }
                            }
                        });
                    }

                    @Override
                    public void onFailure(String result) {
                        LogUtils.d("kf5测试", "登录失败" + result);
                        Constants.CustomerOline = false;
                    }
                });

    }

}
